﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Util;
using IntroduceCompany.Singleton;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [IntroduceCompany.Models.CheckModule(ConstantClass.Backend_Survey_MenuID)]
    public class SurveyController : Controller
    {
        //
        // GET: /Survey/

        #region Backend

        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult QuestionList()
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                //Check Cookie Language
                string languageID = ConstantClass.markViewAllLanguage;
                if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
                {
                    languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
                }
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);
                return View("/Views/Backend/Survey/QuestionList.aspx", DataSingleton.GetSurveyModels().GetQuestionList_Backend(languageID) );

            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult QuestionDelete(int questionID)
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                DataSingleton.GetSurveyModels().DeleteQuestion(questionID);
                return RedirectToAction("QuestionList", "Survey");
            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult ChangeQuestionVisible(int questionID, bool questionVisible)
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                DataSingleton.GetSurveyModels().ChangeQuestionVisible(questionID, questionVisible);
                return RedirectToAction("QuestionList", "Survey");
            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult QuestionCreate()
        {
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", ConstantClass.mainLanguageID);
            return View("/Views/Backend/Survey/QuestionCreate.aspx");

        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult QuestionCreate(QuestionView questionView)
        {

            string username = HttpContext.User.Identity.Name;
            int newQuestionID = 0;

            if (ModelState.IsValid && TryUpdateModel(questionView))
            {
                newQuestionID = DataSingleton.GetSurveyModels().CreateQuestion(questionView, username);
            }

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", questionView.LanguageID);
            if (newQuestionID > 0) // Go to Question Edit after insert successful to insert other language
            {
                return RedirectToAction("QuestionEdit", "Survey", new { questionID = newQuestionID, languageID = questionView.LanguageID });
            }
            else  // Return Product Create if there are any error.
            {
                return View("/Views/Backend/Survey/QuestionCreate.aspx", questionView);
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult QuestionEdit(int questionID, String languageID)
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);

                QuestionView oneQuestionView = DataSingleton.GetSurveyModels().GetOneQuestionView(questionID, languageID);

                if (oneQuestionView == null)
                {
                    Question temQues = DataSingleton.GetSurveyModels().GetQuestionByQuestionID(questionID);
                    oneQuestionView = new QuestionView();
                    oneQuestionView.QuestionID = temQues.QuestionID;
                    //oneQuestionView.LanguageID = languageID;
                    oneQuestionView.Location = temQues.Location;
                    oneQuestionView.QuestionUpdateDate = temQues.QuestionUpdateDate;
                    oneQuestionView.QuestionCreateDate = temQues.QuestionCreateDate;
                    oneQuestionView.UserName = temQues.UserName;
                    oneQuestionView.FullName = temQues.Administrator.FullName;
                }

                return View("/Views/Backend/Survey/QuestionEdit.aspx", oneQuestionView);
            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }

        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult QuestionEditSubmit(QuestionView questionView)
        {

            string username = HttpContext.User.Identity.Name;

            //Edit information of product when press Save button. Not Edit when change language
            if (DataSingleton.GetSurveyModels().CheckQuestionLanguageIsExisted(questionView)  )
            {

                //Edit question
                if (ModelState.IsValid && TryUpdateModel(questionView) && DataSingleton.GetSurveyModels().UpdateQuestion(questionView, username))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Câu hỏi đã được cập nhật.");
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật câu hỏi.");
                }
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName"
                    , questionView.LanguageID);

                return View("/Views/Backend/Survey/QuestionEdit.aspx", DataSingleton.GetSurveyModels().GetOneQuestionView(questionView.QuestionID
                    , questionView.LanguageID));

            }
            else
            {
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName"
                    , questionView.LanguageID);

                if (ModelState.IsValid && TryUpdateModel(questionView) && DataSingleton.GetSurveyModels().InsertQuestionLanguage(questionView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Câu hỏi đã được cập nhật thêm ngôn ngữ mới.");

                    return View("/Views/Backend/Survey/QuestionEdit.aspx", DataSingleton.GetSurveyModels().GetOneQuestionView(questionView.QuestionID
                        , questionView.LanguageID));
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thêm ngôn mới cho câu hỏi.");

                    return View("/Views/Backend/Survey/QuestionEdit.aspx", questionView);
                }
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult AnswerList(int questionID)
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                //Check Cookie Language
                String languageID = ConstantClass.markViewAllLanguage;
                if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
                {
                    languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
                }

                ViewData["QuestionID"] = questionID;
                ViewData["QuestionContent"] = DataSingleton.GetSurveyModels().GetQuestionContent(questionID,
                        languageID == ConstantClass.markViewAllLanguage ? ConstantClass.mainLanguageID : languageID);
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);
                return View("/Views/Backend/Survey/AnswerList.aspx", DataSingleton.GetSurveyModels().GetAnswerList_Backend(questionID, languageID));

            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult AnswerDelete(int answerID, int questionID)
        {
            DataSingleton.GetSurveyModels().DeleteAnswer(answerID);
            return RedirectToAction("AnswerList", "Survey", new { questionID = questionID });
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult AnswerCreate(int questionID)
        {
            AnswerView temAnsView = new AnswerView();
            temAnsView.QuestionID = questionID;
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", ConstantClass.mainLanguageID);
            return View("/Views/Backend/Survey/AnswerCreate.aspx", temAnsView);
        }


        [Authorize(Roles = ConstantClass.autSurvey)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AnswerCreate(AnswerView answerView)
        {

            string username = HttpContext.User.Identity.Name;
            int newAnswerID = 0;

            if (ModelState.IsValid && TryUpdateModel(answerView))
            {
                newAnswerID = DataSingleton.GetSurveyModels().CreateAnswer(answerView, username);
            }

            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", answerView.LanguageID);
            if (newAnswerID > 0) // Go to Question Edit after insert successful to insert other language
            {
                return RedirectToAction("AnswerEdit", "Survey", new { answerID = newAnswerID, languageID = answerView.LanguageID });
            }
            else  // Return Product Create if there are any error.
            {
                return View("/Views/Backend/Survey/AnswerCreate.aspx", answerView);
            }
        }



        [Authorize(Roles = ConstantClass.autSurvey)]
        public ActionResult AnswerEdit(int answerID, String languageID)
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Survey", "QuestionList"))
            {
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);

                AnswerView oneAnswerView = DataSingleton.GetSurveyModels().GetOneAnswerView(answerID, languageID);

                if (oneAnswerView == null)
                {
                    Answer temAns = DataSingleton.GetSurveyModels().GetAnswerByAnswerID(answerID);
                    oneAnswerView = new AnswerView();
                    oneAnswerView.QuestionID = temAns.QuestionID;
                    oneAnswerView.ChoosenAmount = temAns.ChoosenAmount;
                    oneAnswerView.AnswerCreateDate = temAns.AnswerCreateDate;
                    oneAnswerView.AnswerUpdateDate = temAns.AnswerUpdateDate;
                    oneAnswerView.UserName = temAns.UserName;
                    oneAnswerView.FullName = temAns.Administrator.FullName;
                }

                return View("/Views/Backend/Survey/AnswerEdit.aspx", oneAnswerView);
            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }



        [Authorize(Roles = ConstantClass.autSurvey)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AnswerEditSubmit(AnswerView answerView)
        {

            string username = HttpContext.User.Identity.Name;

            //Edit information of product when press Save button. Not Edit when change language
            if (DataSingleton.GetSurveyModels().CheckAnswerLanguageIsExisted(answerView) )
            {

                //Edit question
                if (ModelState.IsValid && TryUpdateModel(answerView) && DataSingleton.GetSurveyModels().UpdateAnswer(answerView, username))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Câu trả lời đã được cập nhật.");
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật câu trả lời.");
                }
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName"
                    , answerView.LanguageID);

                return View("/Views/Backend/Survey/AnswerEdit.aspx", DataSingleton.GetSurveyModels().GetOneAnswerView(answerView.AnswerID
                    , answerView.LanguageID));
            }
            else
            {
                //Insert another language for answer
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName"
                    , answerView.LanguageID);

                if (ModelState.IsValid && TryUpdateModel(answerView) && DataSingleton.GetSurveyModels().InsertAnswerLanguage(answerView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Câu trả lời đã được cập nhật thêm ngôn ngữ mới.");

                    return View("/Views/Backend/Survey/AnswerEdit.aspx", DataSingleton.GetSurveyModels().GetOneAnswerView(answerView.AnswerID
                        , answerView.LanguageID));
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thêm ngôn mới cho câu trả lời.");

                    return View("/Views/Backend/Survey/AnswerEdit.aspx", answerView);
                }
            }
        }
     
        #endregion


        #region Frontend

        public ActionResult SurveyPage()
        {
            //Check Cookie Language
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            return View("/Views/Frontend/Survey/SurveyPage.aspx", DataSingleton.GetSurveyModels().GetQuestionList_Frontent(languageID));
        }

        [HttpPost]
        public ActionResult Poll(FormCollection postedForm)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            string componentName ="";
            if (CaptchaController.IsValidCaptchaValue(postedForm["captchaValue"].ToString()))
            {
                foreach (var item2 in postedForm)
                {
                    componentName = item2.ToString();
                    //string ss = postedForm[tt].ToString();
                    if (postedForm[componentName].ToString().Contains("true_true"))
                    {
                        DataSingleton.GetSurveyModels().UpdateTotalChooser(Convert.ToInt16(componentName));
                    }
                }
                ModelState.AddModelError("Notice", "Cám ơn đã đóng góp.");
            }
            else 
            {
                ModelState.AddModelError("Notice", "Nhập chuỗi ký tự trong hình.");
            }
            return View("/Views/Frontend/Survey/SurveyPage.aspx", DataSingleton.GetSurveyModels().GetQuestionList_Frontent(languageID));
        }

        public ActionResult ResultPage()
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            return View("/Views/Frontend/Survey/ResultPage.aspx", DataSingleton.GetSurveyModels().GetQuestionList_Frontent(languageID));
        }

        #endregion
    }
}
